var vueObj = new Vue({
    el: "#vue",
    data: {
        orgObj: oneOrgInfo
    }
});

$(function () {
    if (editType != 'info') {
        regValidate(["#_orgDataForm"]);
        initTextSearch("#isvName",
            basePath + 'org/getIsvData?t='+new Date().getTime()+'&isvName=',
            ['isvPid', 'isvName'],
            {'isvPid':'服务商PID', 'isvName':'服务商名称'},
            'isvPid',
            'isvName',
            true,
            selectIsvValue,
            noSelectIsvValue);
        var orgId = !oneOrgInfo.id ? '' : oneOrgInfo.id;
        initTextSearch("#orgParentCodeStr",
            basePath + 'org/getParentOrgData?t='+new Date().getTime()+'&id='+orgId+'&orgName=',
            ['orgCode', 'orgName'],
            {'orgCode':'机构编码', 'orgName':'机构名称'},
            'orgCode',
            'orgName',
            true,
            selectOrgValue,
            noSelectOrgValue);
    }
});

function selectIsvValue(data) {
    if (!data || !data.isvPid) {
        return;
    }
    $('#isvPid').val(data.isvPid);
}

function noSelectIsvValue() {
    $('#isvPid').val('');
}

function selectOrgValue(data) {
    if (!data || !data.orgCode) {
        return;
    }
    $('#orgParentCode').val(data.orgCode);
}

function noSelectOrgValue() {
    $('#orgParentCode').val('');
}

function doChangeRegionEvent() {
    var region = $('#orgRegion').val();
    if (region == 'main') {
        $('#_parentOrgDiv').hide();
        $('#orgParentCode').val('');
        $('#orgParentCodeStr').val('');
        $('#orgParentCodeStr').attr('class', 'form-control');
        $('#_parentOrgTip').html('');
    } else {
        $('#_parentOrgDiv').show();
    }
}

function doSelectCity() {
    var province = $('#provinceCode').val();
    if (!province || province == '') {
        $('#cityCode').val('');
        var str = '<option value="">--请选择--</option>';
        $('#cityCode').html(str);
    } else {
        province = province.substring(0, 2);
        var postData = {
            dictCode : province,
            groupCode : 'CITY_CODE'
        };
        $.ajax({
            type: 'post',
            url: basePath + 'org/selectCity?t=' + new Date().getTime(),
            dataType: 'json',
            data: postData,
            success : function (data) {
                if(data && data.result){
                    setAreaSelect(data.content, 'cityCode');
                }else if(data&&!data.result){
                    toastr.error(data.message);
                }else{
                    toastr.error('获取城市信息失败');
                }
            },
            error: function (request) {
                delayToastr(common_system_error);
            }
        });
    }
}

function setAreaSelect(list, id) {
    $('#' + id).val('');
    var htmlStr = '<option value="">--请选择--</option>';
    if (list) {
        for (var i=0; i<list.length; i++) {
            htmlStr += '<option value="'+list[i].code+'">'+list[i].name+'</option>';
        }
    }
    $('#' + id).html(htmlStr);
}

function doSelectArea() {
    var cityCode = $('#cityCode').val();
    if (!cityCode || cityCode == '') {
        $('#areaCode').val('');
        var str = '<option value="">--请选择--</option>';
        $('#areaCode').html(str);
    } else {
        cityCode = cityCode.substring(0, 4);
        var postData = {
            dictCode : cityCode,
            groupCode : 'AREA_CODE'
        };
        $.ajax({
            type: 'post',
            url: basePath + 'org/selectCity?t=' + new Date().getTime(),
            dataType: 'json',
            data: postData,
            success : function (data) {
                if(data && data.result){
                    setAreaSelect(data.content, 'areaCode');
                }else if(data&&!data.result){
                    toastr.error(data.message);
                }else{
                    toastr.error('获取县区信息失败');
                }
            },
            error: function (request) {
                delayToastr(common_system_error);
            }
        });
    }
}

function doOrgSave() {
    var orgName = $('#orgName').val();
    var orgShortName = $('#orgShortName').val();
    var orgCategory = $('#orgCategory').val();
    var orgLevel = $('#orgLevel').val();
    var orgRegion = $('#orgRegion').val();
    var orgParentCode = '';
    if (orgRegion == 'branch') {
        orgParentCode = $('#orgParentCode').val();
    }
    var contactPhone = $('#contactPhone').val();
    var provinceCode = $('#provinceCode').val();
    var cityCode = $('#cityCode').val();
    var areaCode = $('#areaCode').val();
    var orgStreet = $('#orgStreet').val();
    var orgAddress = getNewAddress();
    var longitude = $('#longitude').val();
    var latitude = $('#latitude').val();
    var isvPid = $('#isvPid').val();
    var searchTags = getLabelNoteStr('_searchTags', false);
    var orgDescription = $('#orgDescription').val();
    var orgLogo = $('#orgLogo').val();
    var orgThumbnail = $('#orgThumbnail').val();
    var orgImg = $('#orgImg').val();
    var code = $('#code').val();
    var postData = {
        orgName : orgName,
        orgShortName : orgShortName,
        orgCategory : orgCategory,
        orgLevel : orgLevel,
        orgRegion : orgRegion,
        orgParentCode : orgParentCode,
        contactPhone : contactPhone,
        orgProvinceCode : provinceCode,
        orgCityCode : cityCode,
        orgAreaCode : areaCode,
        orgStreet : orgStreet,
        orgAddress : orgAddress,
        longitude : longitude,
        latitude : latitude,
        isvPid : isvPid,
        searchTags : searchTags,
        orgLogo : orgLogo,
        orgThumbnail : orgThumbnail,
        orgImg : orgImg,
        code : code,
        orgDescription : orgDescription
    };
    var url = basePath + 'org/addOrg';
    if (editType == 'edit') {
        postData.id = oneOrgInfo.id;
        url = basePath + 'org/editOrg';
    }
    showLoading();
    $.ajaxFileUpload({
        type: 'post',
        url: url,
        dataType: 'json',
        secureuri : false,
        fileElementId : ["orgLogoFile", "orgThumbnailFile", "orgImgFile"],
        contentType : "application/json; charset=UTF-8",
        data: postData,
        success : function (data) {
            hideLoading();
            if (!data) {
                toastr.error(common_save_fail);
                return;
            }
            if (data.isSuccess) {
                doBack();
                return;
            }
            if (!data.isSuccess && data.errorCode == 'EXIST') {
                toastr.warning('【'+orgName+'】已存在');
                return;
            }
            if (!data.isSuccess) {
                toastr.error(data.errorDesc);
                return;
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
            return;
        }
    });
}

//设置详细地址
function getNewAddress() {
    var province = $("#provinceCode").find("option:selected").text();
    var city = $("#cityCode").find("option:selected").text();
    var area = $("#areaCode").find("option:selected").text();
    var orgStreet = $('#orgStreet').val();
    return format(province) + format(city) + format(area) + orgStreet;
}

function format(str) {
    if (!str || str == '' || str == '--请选择--') {
        return '';
    }
    return str;
}

function checkLogo() {
    if(!$("#_orgDataForm").valid()) return;//校验不通过
    var orgThumbnail = $('#orgThumbnail').val();
    imgSrcDefault;
    var img = $('#_orgThumbnail').attr('src');
    if ((!img || img == '' || img == imgSrcDefault) && (!orgThumbnail || orgThumbnail == '')) {
        toastr.error('机构缩略图不能为空');
        return;
    }

    var idList = ['orgLogoFile', 'orgThumbnailFile', 'orgImgFile'];
    var sizeList = [10*1024, 40*1024, 60*1024];
    var msgList = ["您上传的图片【机构logo】大小超出限制范围（10k以内），无法上传，请重新上传符合要求的图片！", "您上传的图片【机构缩略图】大小超出限制范围（40k以内），无法上传，请重新上传符合要求的图片！", "您上传的图片【机构大图】大小超出限制范围（60k以内），无法上传，请重新上传符合要求的图片！"];
    filesSizeCheck(idList, sizeList, msgList, checkFileChiCun);
}

function checkFileChiCun() {
    var imageList = [];
    var image1 = {
        imageName : '机构logo',
        fileId: 'orgLogoFile',
        imageId : '_orgLogo',
        fileWidth : 100,
        fileHeight : 100,
    };
    var image2 = {
        imageName : '机构缩略图',
        fileId: 'orgThumbnailFile',
        imageId : '_orgThumbnail',
        fileWidth : 160,
        fileHeight : 110,
    };
    var image3 = {
        imageName : '机构大图',
        fileId: 'orgImgFile',
        imageId : '_orgImg',
        fileWidth : 690,
        fileHeight : 320,
    };
    imageList.push(image1);
    imageList.push(image2);
    imageList.push(image3);
    filesChiCunCheck(imageList, doOrgSave);
}

function doCheckDataChange() {
    var orgName = $('#orgName').val();
    var orgShortName = $('#orgShortName').val();
    var orgCategory = $('#orgCategory').val();
    var orgLevel = $('#orgLevel').val();
    var orgRegion = $('#orgRegion').val();
    var orgParentCode = '';
    var contactPhone = $('#contactPhone').val();
    var provinceCode = $('#provinceCode').val();
    var cityCode = $('#cityCode').val();
    var areaCode = $('#areaCode').val();
    var orgStreet = $('#orgStreet').val();
    var longitude = $('#longitude').val();
    var latitude = $('#latitude').val();
    var isvPid = $('#isvPid').val();
    var code = $('#code').val();
    var searchTags = getLabelNoteStr('_searchTags', false);
    var orgDescription = $('#orgDescription').val();
    var orgLogo = $('#orgLogo').val()?$('#orgLogo').val():$('#orgLogoHidden').val();
    var orgThumbnail = $('#orgThumbnail').val()?$('#orgThumbnail').val():$('#orgThumbnailHidden').val();
    var orgImg = $('#orgImg').val()?$('#orgImg').val():$('#orgImgHidden').val();
    var checkData = {
        orgName : orgName,
        orgShortName : orgShortName,
        orgCategory : orgCategory,
        orgLevel : orgLevel,
        orgRegion : orgRegion,
        contactPhone : contactPhone,
        orgProvinceCode : provinceCode,
        orgCityCode : cityCode,
        orgAreaCode : areaCode,
        orgStreet : orgStreet,
        longitude : longitude,
        latitude : latitude,
        isvPid : isvPid,
        searchTags : searchTags,
        orgLogo : orgLogo,
        orgThumbnail : orgThumbnail,
        orgImg : orgImg,
        code : code,
        orgDescription : orgDescription
    };
    if (orgRegion == 'branch') {
        checkData.orgParentCode = $('#orgParentCode').val();
    }
    console.log(oneOrgInfo);
    if (editType != 'info' && (!Compare(checkData, oneOrgInfo) || $("#orgLogoFile").val()!='' || $("#orgThumbnailFile").val()!='' || $("#orgImgFile").val()!='')) {
        swalClosePageToastr(doBack);
        return;
    }
    doBack();
}

function doBack() {
    var str = (!searchOrgInfo.isMerge || searchOrgInfo.isMerge == '') ? '' : ('&isMerge=' + searchOrgInfo.isMerge);
    window.location.href = basePath + 'org/orgPage?t=' + new Date().getTime() + '&orgName=' + searchOrgInfo.orgName +
        '&isvPid=' + searchOrgInfo.isvPid + '&isvName=' + searchOrgInfo.isvName + '&status=' + searchOrgInfo.status +
        '&dataStatus=' + searchOrgInfo.dataStatus + '&province=' + searchOrgInfo.province +
        '&city=' + searchOrgInfo.city + str + '&pageNo=' + searchOrgInfo.pageNo + '&pageSize=' + searchOrgInfo.pageSize;
}

function openEnumListPage() {
    var searchTags = getLabelNoteStr('_searchTags', false);
    $('#enumListTable').bootstrapTable('refresh', {
        url: basePath + 'org/pageFindBizEnumData?t=' + new Date().getTime(),
        query: {
            enumNames : searchTags,
        },
    });
    $('#enumListPage').modal('show');
}

function closeEnumListPage() {
    $('#enumListPage').modal('hide');
}

$('#enumListTable').on("click-row.bs.table", function (e, row, $element) {
    // checkBox 的勾选
    var index = $element[0].rowIndex - 1;
    $('#enumListTable').bootstrapTable('check', index);
});

function doSelectTagsEvent() {
    var tagList=[];
    var tags=getSelectedRows('#enumListTable');
    for (var cell in tags){
        tagList.push({value:tags[cell].enumName, text:tags[cell].enumName});
    }
    $('#enumListPage').modal('hide');
    addLableByList(tagList, "_searchTags");
}

function openGeocoderMapPage() {
    var orgStreet = $("#orgStreet").val();
    var oldOrgAddress = $("#oldOrgAddress").val();
    var newOrgAddress = getNewAddress();
    var s_marker;
    if(!orgStreet){
        toastr.error("请先输入详细地址");
        return;
    }
    var map = new AMap.Map('allMap', {
        resizeEnable: true
    });
    //单击获取点击的经纬度
    var clickEventListener = map.on('click', function(e) {
        $("#longitudeValue").html(e.lnglat.lng);
        $("#longitude").val(e.lnglat.lng);
        $("#latitudeValue").html(e.lnglat.lat);
        $("#latitude").val(e.lnglat.lat);
        if (s_marker) {
            map.remove(s_marker);
        }
        s_marker = new AMap.Marker({
            position: new AMap.LngLat(e.lnglat.lng, e.lnglat.lat),
        });
        map.add(s_marker);
    });
    if(oldOrgAddress == newOrgAddress){
        //地址未变更----使用经纬度检索
        var longitude = $("#longitude").val();
        var latitude = $("#latitude").val();
        $('#longitudeValue').html(longitude);
        $('#latitudeValue').html(latitude);
        if (longitude && latitude) {
            var pos = [longitude, latitude];
            map.setZoomAndCenter(16, pos);
            setTimeout(function () {
                s_marker = new AMap.Marker({
                    position: new AMap.LngLat(longitude, latitude),
                });
                map.add(s_marker);
            }, 500);
        }
    } else {
        var geocoder = new AMap.Geocoder({});
        geocoder.getLocation(newOrgAddress, function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
                var geocode = result.geocodes;
                if(!geocode || !geocode.length>0){
                    toastr.error('获取经纬度失败');
                    return;
                }
                var _lng = geocode[0].location.getLng();
                var _lat = geocode[0].location.getLat();
                var pos = [_lng, _lat];
                map.setZoomAndCenter(16, pos);
                setTimeout(function () {
                    s_marker = new AMap.Marker({
                        position: new AMap.LngLat(_lng, _lat),
                    });
                    map.add(s_marker);
                }, 500);
                $("#longitudeValue").html(_lng);
                $("#longitude").val(_lng);
                $("#latitudeValue").html(_lat);
                $("#latitude").val(_lat);
            }else{
                toastr.error('获取经纬度失败');
                return;
            }
        });
    }
    $('#geocoderMapPage').modal('show');
}

function closeGeocoderMapPage() {
    $('#geocoderMapPage').modal('hide');
    $('#allMap').empty();
}
